import { PiniaPluginContext, StateTree } from "pinia"
import { PINIA_CACHE_KEY } from "../config/common.cfg"
import { decodeApi, encodeApi } from "../utils"

/**
 * 持久化方法
 * @param {params: PiniaPluginContext} param0 
 */
export default function persisteStatePlugin({ store }: PiniaPluginContext) {
    store.$subscribe(function(_: any, _state: StateTree) {
        sessionStorage.setItem(PINIA_CACHE_KEY, encodeApi(JSON.stringify(_state)))
    })
}

/**
 * 初始化state数据
 * @returns any
 */
export function initState() {
    let cache = sessionStorage.getItem(PINIA_CACHE_KEY)

    if (!cache) {
        return {}
    } else {
        try {
            return JSON.parse(decodeApi(cache))
        } catch {
            return {}
        }
    }
}